import React,{createContext,useContext, useEffect} from 'react'
import {useLocalStorage} from './use-storage'


const Context = createContext();
export const TransProvider=({i18n,children})=>{
    if(!i18n){
        throw new Error('no i18n provide');
    }
    let [lang,setLang]=useLocalStorage('lang',undefined)
    const [locales,setLocales]=useLocalStorage('locales',undefined)
    console.log(locales);
    useEffect(()=>{
      let currentLang=lang;
      if(!lang){
          const {navigator}=window;
          currentLang=navigator.language;
          setLang(currentLang); 
          return ;
      } 
      if(!locales ||
          !locales.date ||
          !locales.lang ||
          locales.lang !== currentLang ||
          Date.now()-locales.date > 86400000
          ){
              setLocales({data:i18n[currentLang],lang:currentLang,date:Date.now()})
          }
    })
    const getMessage=()=>locales.data

    const setNewLang=newLang=>{
        setLang(newLang);
        setLocales({data:i18n[newLang],lang:newLang,data:Date.now()})
    }

    if(!locales) return <div>loading...</div>
    // let lang=window.navigator.language;
    return (
        <Context.Provider value={{
            lang,
            getMessage,
            locales,
            setNewLang
        }}>
            {children}
        </Context.Provider>
    )
}

export const useI18n=(path)=>{
    const {getMessage} = useContext(Context)
    return getMessage(path)
}

export const setLang=()=>{
    const {lang,setNewLang}=useContext(Context);
    return [lang,setNewLang]
}